//
//  StatusListViewModel.swift
//  SinaWeibo
//
//  Created by yang on 15/11/16.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage
class StatusListViewModel: NSObject {
    //获取当前登录用户及其所关注用户的最新微博
    func loadData(since_id since_id:Int, max_id: Int,
        finished:(array:[Status]?) -> ()){
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().tooken else {
            SVProgressHUD.showErrorWithStatus("未登录")
            return
        }
        var parameters = ["access_token":token]
            if since_id > 0{
             parameters["since_id"] = "\(since_id)"
           }
            if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
            
            }
    NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
        if error != nil{
            finished(array:nil)
            return 
        }
        if let array = dict!["statuses"] as?[[String:AnyObject]]{
            var list = [Status]()
            for item in array{
                let s = Status(dict: item)
                list.append(s)
        }
        self.cacheStatusImage(list, finished: finished)
        }
    }
  }
    //完成单张图片的缓存
    private func cacheStatusImage(array: [Status],finished:(array:[Status]?) -> ()){
        if array.count == 0{
        finished(array: array)  
        return
        }
        let group = dispatch_group_create()
        for s in array{
            if let urlImages = s.url {
                if urlImages.count != 1{
                  continue
                }
                for url in urlImages{
                dispatch_group_enter(group)
                 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                 })
                }
            }
        }
       dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
        finished(array: array)
        }
    
    }
}


